package com.zhentao.config;


import cn.hutool.json.JSONUtil;
import com.zhentao.common.AppJwtUtil;
import com.zhentao.util.Result;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author : mgh
 * @date : 2024-06-25 21:12
 * @effect : 当前类的作用是
 * @projectTeam :
 */
@Component
public class LoginFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //1获取到url，判断是否是登陆
        String url = request.getURI().getPath();
        if (url.contains("/user/login")){
            //放行
            return chain.filter(exchange);
        }

        String token = request.getHeaders().getFirst("token");
        //2说明不是登录接口，判断是否登录
        //获取token
        if (StringUtils.isBlank(token)){
            response.getHeaders().add("Content-Type","application-json");
            String str = JSONUtil.toJsonStr(Result.error(401, "token失效或者不存在"));
            DataBuffer wrap = response.bufferFactory().wrap(str.getBytes());
            return response.writeWith(Mono.just(wrap));
        }

        //3token获取到了，判断token是否有效
        try {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            int verifyToken = AppJwtUtil.verifyToken(claimsBody);
            if (verifyToken == 1 || verifyToken == 2){
                response.getHeaders().add("Content-Type","application-json");
                String str = JSONUtil.toJsonStr(Result.error(401, "token失效或者不存在"));
                DataBuffer wrap = response.bufferFactory().wrap(str.getBytes());
                return response.writeWith(Mono.just(wrap));
            }
            //获取token中的id
            Object id = claimsBody.get("id");
            //把id放入到header
            request.mutate().headers(header->header.add("userId",id+""));
            //更新request 放回请求
            exchange.mutate().request(request).build();

        } catch (Exception e) {
            response.getHeaders().add("Content-Type","application-json");
            String str = JSONUtil.toJsonStr(Result.error(401, "token失效或者不存在"));
            DataBuffer wrap = response.bufferFactory().wrap(str.getBytes());
            return response.writeWith(Mono.just(wrap));
        }
        //4token有效放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        ///权重等级
        return 0;
    }
}
